﻿Imports Microsoft.LightSwitch.Threading
Imports System.Windows

Namespace LightSwitchApplication

    Public Class CreateNew




        Public Shared Sub PromptAndImportEntities(ByVal entitySetToCreateIn As IEntitySet)

            Dim file As IO.FileInfo = Nothing

            ' OpenFileDialog() must be opened on the UI thread

            Dispatchers.Main.Invoke(Sub()

                                        Dim dlg As New Controls.OpenFileDialog
                                        dlg.Filter = "CSV Files (*.csv)|*.csv|Text Files (*.txt)|*.txt"

                                        If dlg.ShowDialog = True Then
                                            file = dlg.File
                                        End If
                                    End Sub)
            If (Not file Is Nothing) Then
                PerformImport(file, entitySetToCreateIn)
            End If
        End Sub



        Private Shared Sub PerformImport(ByVal file As IO.FileInfo, ByVal entitySetToCreateIn As IEntitySet)

            Using reader As IO.StreamReader = file.OpenText
                Dim inputLine As String = reader.ReadLine

                ' Get the property names from the first line of input
                Dim headers As String() = inputLine.Split(",").Select(Function(header As String) header.Trim).ToArray()
                For Each header In headers
                    header = header.Trim
                Next

                Dim count As Int16 = headers.Count

                Dim data As String()

                inputLine = reader.ReadLine

                While Not inputLine Is Nothing

                    data = inputLine.Split(",")

                    ' If the right number of data items were found, import the line
                    If data.Count = count Then
                        ImportSingle(entitySetToCreateIn, headers, data)
                    Else
                        Throw New InvalidOperationException(String.Format("Line not imported.  Invalid number of elements.  Data = [{0}].", inputLine))
                    End If
                    inputLine = reader.ReadLine
                End While

                reader.Close()

            End Using

            entitySetToCreateIn.Details.DataService.SaveChanges()

        End Sub



        Private Shared Sub ImportSingle(ByVal entitySetToCreateIn As IEntitySet, ByVal headers As String(), ByVal data As String())

            ' Create the new entity
            Dim newEntity As IEntityObject = entitySetToCreateIn.AddNew()
            Dim currentProperty As Microsoft.LightSwitch.Details.IEntityProperty
            Dim newValue As Object

            ' Loop through all propertyNames from the first line of the file
            For index As Integer = 0 To headers.Count - 1
                Try
                    ' Get the property from the new entity by name
                    currentProperty = newEntity.Details.Properties(headers(index))
                Catch ex As ArgumentException
                    Throw New InvalidOperationException(String.Format("A property named {0} does not exist on the entity named {1}.", headers(index), newEntity.Details.Name))
                End Try

                Try
                    ' Convert the value
                    newValue = Convert.ChangeType(data(index), currentProperty.PropertyType, Nothing)
                    currentProperty.Value = newValue
                Catch ex As System.FormatException
                    Throw New InvalidOperationException(String.Format("The following line has an invalid value for property {0}.  Aborting the import." + vbNewLine + "Data: {1}", headers(index), String.Join(",", data)))
                End Try
            Next
        End Sub

        Private Sub ImportMethod_Execute()
            ' Write your code here.
            'PromptAndImportEntities(Me.DataWorkspace.jokoatsData.MainAssetsTables)
            UpdateRFIDData()
        End Sub

        Private Sub UpdateRFIDData()
            Dim recordCtr As Integer = 0
            Dim SearchCriteria As String = String.Empty
            Dim localLocation As String = String.Empty
            Dim opnfile As IO.FileInfo = Nothing

            Try
                Dim path As String = "D:\Test Projects\New\"
                Dim CriteriaPath, files As String ', filename As String

                CriteriaPath = path.Substring(0, path.LastIndexOf("\"))

                If SearchCriteria.Length = 0 Then
                    SearchCriteria = "*.txt"
                Else
                    SearchCriteria = path.Substring(path.LastIndexOf("\") + 1)
                End If

                For Each files In IO.Directory.EnumerateFiles(CriteriaPath, SearchCriteria)

                    '        Dim parser As New fileIO.TextFieldParser(files)
                    '        parser.TextFieldType = FileIO.FieldType.Delimited
                    '        parser.SetDelimiters(" ")
                    '        While Not parser.EndOfData
                    '            parser.ReadFields()
                    '        End While
                    '        parser.Close()
                    '        parser = New FileIO.TextFieldParser(files)
                    '        parser.TextFieldType = FileIO.FieldType.Delimited
                    '        parser.SetDelimiters(" ")

                    '        Dim currentRow() As String
                    '        Dim fldCtr As Integer
                    '        While Not parser.EndOfData
                    '            fldCtr = 1
                    '            Try
                    '                currentRow = parser.ReadFields()
                    '                Dim currentField As String
                    '                For Each currentField In currentRow
                    '                    If fldCtr = 2 Then
                    '                        Dim rfidNumber As String = Mid(currentRow(1), currentRow(1).Length - 9, 10)
                    '                        Dim rfidScanDate As Date = CDate(Mid(filename, 1, 4) & "/" & Mid(filename, 5, 2) & "/" & Mid(filename, 7, 2))
                    '                        Dim RFIDDateScanned = From RFIDTable In dbRFIDScanTable.RFIDScanHistories.Where(Function(o) o.RFIDNum = rfidNumber And o.DateScanned = rfidScanDate)
                    '                        If RFIDDateScanned.Count = 0 Then
                    '                            Dim RFIDScannedTable As New RFIDScanHistory
                    '                            With RFIDScannedTable
                    '                                .DateScanned = rfidScanDate
                    '                                .RFIDNum = rfidNumber
                    '                            End With
                    '                            dbRFIDScanTable.RFIDScanHistories.InsertOnSubmit(RFIDScannedTable)
                    '                        End If
                    '                        Dim itemsTable = From ATSItemsTable In dbRFIDScanTable.MainAssetsTables _
                    '                                         Where ATSItemsTable.RFIDno = rfidNumber
                    '                        If itemsTable.Count > 0 Then
                    '                            With itemsTable.First
                    '                                .LastScanDate = rfidScanDate
                    '                            End With
                    '                        Else
                    '                            If Not listboxNotonDatabase.Items.Contains(rfidNumber) Then
                    '                                listboxNotonDatabase.Items.Add(rfidNumber)
                    '                                listboxNotonDatabase.Items.Refresh()
                    '                            End If
                    '                        End If
                    '                        dbRFIDScanTable.SubmitChanges()

                    '                        'Label1.Text &= currentRow(1) & ControlChars.Lf
                    '                        recordCtr += 1
                    '                    End If
                    '                    fldCtr += 1
                    '                Next
                    '            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    '                MsgBox("Line " & ex.Message & _
                    '                "is not valid and will be skipped.")
                    '            End Try
                    '        End While
                    '        parser.Close()

                    '        FileFound += 1
                    '        If File.Exists(files) Then
                    '            File.Move(files, Mid(files, 1, files.Length - 3) & Format(Now(), "ddMMyyhhmmss"))
                    '        Else
                    '            File.Move(files, Mid(files, 1, files.Length - 3) & "old")
                    '        End If

                Next

                '    imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
                '    imgUpdateDatabaseOk.Visibility = Windows.Visibility.Visible
                '    PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden

                '    lblNumberofRecordsProcessed.Content = recordCtr
            Catch ex As Exception
                '    MsgBox("Please check format of reader files.")
                '    imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
                '    imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                '    PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
            End Try
        End Sub
    End Class

End Namespace
